package edu.friday.repository;

import edu.friday.model.User;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Integer> {

    List<User> findByUsernameContaining(String username);

    List<User> findByMajorContaining(String major);

    List<User> findByUsernameContainingAndMajorContaining(String username, String major);

    // 新增方法：检查用户名是否存在
    boolean existsByUsername(String username);

    // 新增方法：通过ID查询用户
    Optional<User> findById(Integer id);

    // 新增方法：检查用户名是否存在（排除指定ID的用户）
    @Query("SELECT COUNT(u) > 0 FROM User u WHERE u.username = :username AND u.id != :id")
    boolean existsByUsernameAndIdNot(@Param("username") String username, @Param("id") Integer id);

    // 新增方法：逻辑删除用户
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.delFlag = 2 WHERE u.id = :id AND u.delFlag = 0")
    int logicalDeleteById(@Param("id") Integer id);
}